<?php

namespace app\Modules\Api\models;

use Yii;
use app\models\Auction as BaseModel;

/**
 * LoginForm is the model behind the login form.
 *
 * @property user|null $user This property is read-only.
 *
 */
class Auction extends BaseModel
{
    public function fields()
    {
        $fields = parent::fields();
        $strvalfields = [
            'auctionid',
            'product_id',
            'market_val',
            'cost',
            'return_rate',
            'start_price',
            'scope',
            'fee',
            'degree',
            'lowest_price',
            'highest_price',
            'default_price',
            'actcount',
            'reacount',
            'can_robot',
            'have_cost',
            'can_give',
            'state',
            'periods',
            'price',
            'user_id',
        ];

        foreach($strvalfields as $strvalfield){
            $fields[$strvalfield] = function() use ($strvalfield){
                return strval($this->$strvalfield);
            };
        }
        $dateFields = ['end_at','created_at','updated_at'];
        foreach($dateFields as $dateField){
            $fields[$dateField] = function() use($dateField){
                return Date('Y-m-d G:i:s',$this->$dateField);
            };
        }

//        unset($fields['created_at'],$fields['updated_at']);
        return $fields;
    }

    public function extraFields(){
        return [
            'uimg'=>function(){
                $user_id = $this->user_id;
                $user = User::findOne($user_id);
                return $user&&$user->img?Yii::$app->params['uploadUrl'].$user->img:'';
            },
            'pname'=>function(){
                $product = $this->product;
                return $product?$product->name:'';
            },
            'pspec'=>function(){
                $product = $this->product;
                return $product?$product->spec:'';
            },
            'auction_state'=>function(){
                return strval($this->state);
            },
            'cut'=>function(){
                return $this->getCut();
            }
        ];
    }

    public function getCut()
    {
        $cut = ($this->market_val-$this->price)*100/$this->market_val;
        if($cut<0){
            return '0.00%';
        }
        return sprintf('%0.2f',$cut).'%';
    }
}